package org.boyan.download.controller;

import org.boyan.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/modules")
public class DownloadModulesController {
    @Value("${boyan.path.upload}")
    private String path;

    //下载导入交易码的excel模板
    @GetMapping("/downloadModule/{filename}")
    public void getTransCodeModule(@PathVariable("filename")String filename, HttpServletResponse response){
        String filepath=path+"/modules/"+filename;
        File file =new File(filepath);
        try {
            FileInputStream in=new FileInputStream(file);
            OutputStream output=response.getOutputStream();
            int len=0;
            byte[] b=new byte[1024];
            //将Content-Disposition暴露出来
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
            while((len=in.read(b))!=-1){
                output.write(b,0,len);
            }
            output.flush();
            output.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/downloadFile")
    public void downloadFile(@RequestBody Map<String,Object> map,HttpServletResponse response){
        String filePath= (String) map.get("file");
        File file=new File(filePath);
        String filename=file.getName();
        try {
            FileInputStream in=new FileInputStream(file);
            OutputStream output=response.getOutputStream();
            int len=0;
            byte[] b=new byte[1024];
            //将Content-Disposition暴露出来
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
            while((len=in.read(b))!=-1){
                output.write(b,0,len);
            }
            output.flush();
            output.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
